/**
 * Created by jiaaobo on 16/11/29.
 */

import CheckList from "../../../common/component/CheckList";
import PickPopup from "../../../common/component/PickPopup";
import DatePopup from "../../../common/component/DatePopup";
import TimeSelection from "../../../common/component/TimeSelection";
import Util from "util";
import API  from "api";
import constant from "const";
import moment from "moment";


export default{
  name: "addOrder",
  data(){

    let data = Util.Storage.getSgObj("orderInfo");
    if(data){
      console.log("加载...",data);
      return data;
    }

    return {
      dateInputStyle: {
        "background": "transparent",
        "box-shadow": "none",
        "border": "0",
        "color" : "#42BD55"
      },
      selectPeopleCount: constant.ORDER.PEOPLE_COUNT[0],

      peopleTypeList : constant.ORDER.PEOPLE_COUNT.map((a)=> { return a.desc  }),

      //时间类型
      selectTimeType : 1,

      //时长
      duration  : 60 * 60 * 1000,

      //选择日期
      selectDate :{
        time :  moment().format('YYYY-MM-DD')
      },

      //选择时间
      selectTime : "",


      showDate: true,

      //欠费情况
      userArrears : "",

      needTo : "",

      //总价格
      total  : "",

      //同行人
      userList : [],

      slots: [
        {
          flex: 1,
          values: Object.keys(constant.ORDER.PEOPLE_COUNT),
          className: 'slot1',
          defaultIndex: 1,
          textAlign: 'center'
        }
      ],
      selectVoucher : '',
      orderState : '',

      //时间段范围筛选
      limit : [
        {
          type: 'fromto',
          from: moment().add(-1,'days') .format('L')
        }
      ]
    }
  },

  created : function(){
    //获得商店详情
    this.store = Util.Storage.getSgObj('storeDetail');
    if(!this.store){
      Util.UI.toast("商店详情为传递!");
      return;
    }

    this.selectVoucher = Util.Storage.getSgObj("voucher");
    //查询小伙伴
    this.loadUserList();
    //查询上次欠费
    this.queryUserArrears();
  },

  mounted: function () {

  },
  methods: {
    toVoucher : function(){
      console.log('存入..',this.$data);
      Util.Storage.setSgObj("orderInfo",this.$data);
      Util.Storage.removeSg("voucher");
      window.getRouter().push({path : '/voucher/list/select'});
    },
    getUserWhole : function(){
      if(this.orderState == 2){
        if(this.userList[0].userId == window.USER_INFO.id){
          return "您已选择包场,其它用户无法预约";
        }
        else{
          return "土豪已包场,请选择其它时段哦";
        }
      }
    },

    calcTotal : function () {
        let time = this.selectTimeType == 1 ? 1 :  this.selectTimeType == 2 ? 1.5 : 2;
        let price = 0;
        console.log('倍数 ',time);
        //人数计算
        if(this.selectPeopleCount.key != "0"){
          price = (this.store.unitPrice * time * this.selectPeopleCount.key).toFixed(2);
        }
        //包场
        else{
          let temp = this.selectTimeType == 1 ? 60 :  this.selectTimeType == 2 ? 90 : 120;
          price = this.store.allPrice[temp];
        }
        this.total = price;
        let needTo = this.total - this.userArrears.overtimeCost;
       //还需支付
        if(this.selectVoucher){
          needTo = needTo  - this.selectVoucher.couponPrice;
        }
        this.needTo = needTo.toFixed(2);
    },

    queryUserArrears : function(){

      API.biz.queryUserArrears({},{hasLoading : true})
        .then(res=>{
          console.log(res,"欠费");
          this.userArrears = res.bizData;
          this.calcTotal();
        });
    },

    changeTimeType : function(val){
      let time = this.getTimeList.filter((a)=>{return a.key == val})[0];
      this.duration = time.duration;
      console.log("old..",this.duration);
      setTimeout((e)=>{
        this.$refs.timeSelectionObj.refresh();
      },1)

      this.calcTotal();

    },

    loadUserList : function(startTime,endTime){

        var params = {
          storeId : this.$route.query.storeId,
          startTime : startTime,
          endTime : endTime
        };

        API.biz.queryTogetherUsers(params,{hasLoading : true})
          .then(res=>{

            this.orderState = res.bizData.state;
            this.userList =  res.bizData.userInfos;
            // let u = [];
            // for(let i =0;i<7;i++){
            //   u.push(res.bizData.userInfos[0]);
            // }
            //this.userList = u;
          });
    },

    //选择人数
    pickpoppupComplete: function (type,val) {
      this.selectPeopleCount = constant.ORDER.PEOPLE_COUNT.filter((p)=>{return p.desc == val[0]})[0];
      this.calcTotal();
    },

    changeDate : function(d){
      //查询小伙伴
      this.loadUserList();
    },


    timeSelectionComplete : function(time){
        this.selectTime = time.hour + ":" + time.min;
        console.log(this.selectTime);
        let nextTime = this.getTimeList.filter((a)=>{return a.key == this.selectTimeType})[0];
        let startTime = new Date(this.selectDate.time + " "+this.selectTime).getTime();
        let endTime   = startTime +  nextTime.duration;
        console.log(startTime,endTime);
        //加载请求
        this.loadUserList(startTime,endTime);
    },

    //支付
    onPay: function () {

      Util.UI.loading("show");
      let startTime = Date.parse((this.selectDate.time+" " +this.selectTime).replace(/-/g, "/"));
      let endTime  = startTime + this.duration;
      console.log('time-->',startTime);
      console.log('time-->',endTime);
      var data = {
        userId : window.USER_INFO.id,
        storeId : this.$route.query.storeId,
        startTime : startTime,
        intervalTime : this.duration / 1000,
        endTime : endTime,
        peopleCount : this.selectPeopleCount.key,
        appointPrice : this.needTo,
        overtimePrice : this.userArrears.overtimeCost
      }

      let orderNo;

      //下单
      API.biz.commitAppoint(data)
        .then((res)=>{
          console.log('订单号-->',res.bizData.orderNo);
          orderNo = res.bizData.orderNo;
          return  API.wx.commitOrder(orderNo);
        })
        .then(res=>{
          Util.UI.loading("hide");
          console.log('下单返回-->',res.bizData);
          let wxParams = {
              timestamp : res.bizData.paymap.timeStamp,
              nonceStr: res.bizData.paymap.nonceStr, // 支付签名随机串，不长于 32 位
              package: res.bizData.paymap.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
              signType: res.bizData.paymap.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
              paySign: res.bizData.paymap.paySign
          };

          Util.WX.wxPay(wxParams)
            .then((res)=>{
              Util.UI.toast("支付成功!");

              window.getRouter().replace({'path' : '/order/my'});

            },(err)=>{
              if(res.state == 500){
                Util.UI.toast("支付失败!");
                console.log(res);
              }
            });
        },err=>{
          Util.UI.loading("hide");
        });
    }

  },

  computed: {
    getUserAccount : function(){
      if(!this.selectVoucher){
        let detail = Util.Storage.getSgObj("userDetail");
        return {'desc' : detail.availableCount + "张可用", type : "view",val : detail.availableCount};
      }
      else{
        let desc = this.selectVoucher.couponName  + " "+ this.selectVoucher.couponPrice + "元";
        return {'val' : this.selectVoucher.couponPrice ,'desc' : desc, type : "select"}
      }
    },

    getTimeList : function(){

      return [
        {
          key: 1,
          value: "60分钟",
          duration : 60 * 60 * 1000
        },
        {
          key: 2,
          value: "90分钟",
          duration : 90 * 60 * 1000
        },
        {
          key: 3,
          value: "120分钟",
          duration : 120 * 60 * 1000
        }
      ]
    }
  },
  components: {
    CheckList,
    PickPopup,
    DatePopup,
    TimeSelection
  }
}
